var map, places = [];

function showPos(pos) {

    var lat = pos.coords.latitude,
    lon = pos.coords.longitude,
    latlon = new google.maps.LatLng(lat, lon),
    mapholder = document.getElementById('mapholder');
    
    //mapholder.style.height = (screen.availHeight-20)+"px";
    //mapholder.style.width = (screen.availWidth-60)+"px";

    var myOptions = {
        center: new google.maps.LatLng(47.677949999999996, 9.17323799999997),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl:false,
        navigationControlOptions:{style: google.maps.NavigationControlStyle.SMALL}
    };
    
    map = new google.maps.Map(mapholder, myOptions);

    addMarker(latlon, "Dein Standort");
    
    var dist = 99999999999999, new_lon, new_lat;
    
    // Lat und Long in der Datei vertauscht...
    $.getJSON('lndw_programm.json', function(data){
        places = data;
        $.each(data, function(index, item){
            addMarker(new google.maps.LatLng(item.long, item.lat), item.place_name);
            if (distance(item.long, item.lat, lat, lon) < dist) {
                dist = distance(item.long, item.lat, lat, lon);
                new_lat = item.long;
                new_lon = item.lat;
            }
        });
        var lineCoordinates = [
            new google.maps.LatLng(lat, lon),
            new google.maps.LatLng(new_lat,new_lon)
        ];
        var line = new google.maps.Polyline({
            path: lineCoordinates,
             geodesic: true,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2,
            map: map
        });
    });
}

function addMarker(location, title) {
    var marker = new google.maps.Marker({
        position: location,
        map: map, 
        title: title
    });
    google.maps.event.addListener(marker, 'click', function() {
        document.getElementById('content').style.backgroundColor = "white";
        document.getElementById('contentholder').style.display = "block";
        document.getElementById('mapholder').style.display = "none";
        document.getElementById('map').style.backgroundColor = "gray";
        getSelectedEvent(title, "table");
    });
}

function getPos() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPos,showError);
    } else {
        document.getElementById('mapholder').innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showError(error) {
    switch(error.code) 
    {
        case error.PERMISSION_DENIED:
            document.getElementById('mapholder').innerHTML="User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            document.getElementById('mapholder').innerHTML="Location information is unavailable."
            break;
        case error.TIMEOUT:
            document.getElementById('mapholder').innerHTML="The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            document.getElementById('mapholder').innerHTML="An unknown error occurred."
            break;
    }
}
  
function distance(lat1, lon1, lat2, lon2) {
	var radlat1 = Math.PI * lat1/180
	var radlat2 = Math.PI * lat2/180
	var radlon1 = Math.PI * lon1/180
	var radlon2 = Math.PI * lon2/180
	var theta = lon1-lon2
	var radtheta = Math.PI * theta/180
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist)
	dist = dist * 180/Math.PI
	dist = dist * 60 * 1.1515
	return dist
}

function changeContent(input) {
    if (input == "map") {
        document.getElementById('contentholder').style.display = "none";
        document.getElementById('content').style.backgroundColor = "gray";
        document.getElementById('mapholder').style.display = "block";
        document.getElementById('map').style.backgroundColor = "white";
        getPos();
    } else if (input == "content") {
        document.getElementById('content').style.backgroundColor = "white";
        document.getElementById('contentholder').style.display = "block";
        document.getElementById('mapholder').style.display = "none";
        document.getElementById('map').style.backgroundColor = "gray";
        getSelectedEvent("", "table");
    }
}

function show(id) {
    console.log('#'+id);
    /*$('#co'+id).animate({"height": "toggle"}, {duration: 500});*/
    $('#co'+id).slideToggle();
    if (document.getElementById('dr'+id).style.backgroundPosition == "0px 0px" || document.getElementById('dr'+id).style.backgroundPosition == "")
        document.getElementById('dr'+id).style.backgroundPosition = "0px -25px";
    else
        document.getElementById('dr'+id).style.backgroundPosition = "0px 0px";
}

/*
Returns:
-1 liegt drunter
0 gleich
1 liegt drin
-2 liegt drüber
*/
function compareTimeString(time) {
    var currentdate = new Date();
    var Std = currentdate.getHours();
    var Min = currentdate.getMinutes();
    var AusgabeStd = ((Std < 10) ? "0" + Std : Std);
    var AusgabeMin = ((Min < 10) ? "0" + Min : Min);
    if (time.indexOf("-") != -1) {
        if (parseInt(time.substr(0,2)) > parseInt(AusgabeStd)) {
            return -1;
        } else if (parseInt(time.substr(0,2)) < parseInt(AusgabeStd) && parseInt(time.substr(time.indexOf(":")+1,2)) < parseInt(AusgabeMin)) {
            if (parseInt(time.substr(time.indexOf("-")+1,2)) < parseInt(AusgabeStd) && parseInt(time.substr(time.indexOf("-")+4,2)) < parseInt(AusgabeMin)) {
                return -2;
            } else {
                return 1;
            }
        } else if (parseInt(time.substr(0,2)) == parseInt(AusgabeStd)) {
            if (parseInt(time.substr(time.indexOf(":")+1,2)) < parseInt(AusgabeMin)) {
                return 1;
            } else if (parseInt(time.substr(3,2)) == parseInt(AusgabeMin)) {
                return 0;
            } else {
                return -1;
            }
        }
    }
    return -1;
}

function buttonBg(place) {
    if (place == "") {
        document.getElementById("all").style.backgroundColor = "yellow";
        document.getElementById("uni").style.backgroundColor = "#dab6e9";
        document.getElementById("htwg").style.backgroundColor = "#eccccc";
        document.getElementById("phtg").style.backgroundColor = "#aaccff";
        document.getElementById("mainau").style.backgroundColor = "#f0acac";
    } else if (place == "Universität Konstanz") {
        document.getElementById("all").style.backgroundColor = "#ccacec";
        document.getElementById("uni").style.backgroundColor = "yellow";
        document.getElementById("htwg").style.backgroundColor = "#eccccc";
        document.getElementById("phtg").style.backgroundColor = "#aaccff";
        document.getElementById("mainau").style.backgroundColor = "#f0acac";
    } else if (place == "HTWG Konstanz") {
        document.getElementById("all").style.backgroundColor = "#ccacec";
        document.getElementById("uni").style.backgroundColor = "#dab6e9";
        document.getElementById("htwg").style.backgroundColor = "yellow";
        document.getElementById("phtg").style.backgroundColor = "#aaccff";
        document.getElementById("mainau").style.backgroundColor = "#f0acac";
    } else if (place == "Insel Mainau") {
        document.getElementById("all").style.backgroundColor = "#ccacec";
        document.getElementById("uni").style.backgroundColor = "#dab6e9";
        document.getElementById("htwg").style.backgroundColor = "#eccccc";
        document.getElementById("phtg").style.backgroundColor = "#aaccff";
        document.getElementById("mainau").style.backgroundColor = "yellow";
    } else if (place == "Kulturzentrum am Münster (Stadt und PHTG)") {
        document.getElementById("all").style.backgroundColor = "#ccacec";
        document.getElementById("uni").style.backgroundColor = "#dab6e9";
        document.getElementById("htwg").style.backgroundColor = "#eccccc";
        document.getElementById("phtg").style.backgroundColor = "yellow";
        document.getElementById("mainau").style.backgroundColor = "#f0acac";
    } 
}

function getSelectedEvent(place, id) {
    element = document.getElementById(id);
    element.innerHTML = '';
    var p = 0;
    if (places == null)
        return;
    buttonBg(place);
    $.each(places, function(index, item){
        p++;
        if (item.place_name == place) {
            var i = 0+p;
            $.each(item.programme_entries, function(key, content){
                i++;
                if (compareTimeString(content.from_to) > -1) {
                    element.innerHTML += '<div class = "but" onclick="show(\''+i+'\')" style="background-color: orange;">\
                    <div class="title"><div class="tri" id="dr'+i+'"></div><div>'+content.from_to+": "+content.title+'</div></div>\
                    <div class="desc" id="co'+i+'">'+content.description+'<br\><br\>Fuer Kinder: '+content.kind+'</div>\
                    <div style="clear: both; height: 0px;"></div>\
                    </div>';
                } else {
                    element.innerHTML += '<div class = "but" onclick="show(\''+i+'\')">\
                    <div class="title"><div class="tri" id="dr'+i+'"></div><div>'+content.from_to+": "+content.title+'</div></div>\
                    <div class="desc" id="co'+i+'">'+content.description+'<br\><br\>Fuer Kinder: '+content.kind+'</div>\
                    <div style="clear: both"></div>\
                    </div>';
                }
            });
            p += i;
        } else if (place == "") {
            var i = 0+p;
            element.innerHTML += '<div class = "but" id="tPlace">\
                    <div class="title">'+item.place_name+'</div>\
                    <div style="clear: both"></div>\
                    </div>';
            $.each(item.programme_entries, function(key, content){
                i++;
                if (compareTimeString(content.from_to) > -1) {
                    element.innerHTML += '<div class = "but" onclick="show(\''+i+'\')" style="background-color: orange;">\
                    <div class="title"><div class="tri" id="dr'+i+'"></div><div>'+content.from_to+": "+content.title+'</div></div>\
                    <div class="desc"  id="co'+i+'">'+content.description+'<br\><br\>Fuer Kinder: '+content.kind+'</div>\
                    <div style="clear: both"></div>\
                    </div>';
                } else {
                    element.innerHTML += '<div class = "but" onclick="show(\''+i+'\')">\
                    <div class="title"><div class="tri" id="dr'+i+'"></div><div>'+content.from_to+": "+content.title+'</div></div>\
                    <div class="desc"  id="co'+i+'">'+content.description+'<br\><br\>Fuer Kinder: '+content.kind+'</div>\
                    <div style="clear: both"></div>\
                    </div>';
                }
            });
            p += i;
        }
    });
}
